package com.jiang.jpa.config.swagger;

import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import java.lang.reflect.Field;
import java.util.Optional;

import static java.util.Optional.empty;
import static springfox.documentation.schema.Annotations.findPropertyAnnotation;
import static springfox.documentation.swagger.schema.ApiModelProperties.findApiModePropertyAnnotation;

/**
 * 通过编写插件实现字段按类变量定义顺序排序,丰富模型属性
 */
@Slf4j
@Component
public class SwaggerModelPropertyBuilderPlugin implements ModelPropertyBuilderPlugin {


    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }


    @Override
    public void apply(ModelPropertyContext context) {
        Optional<ApiModelProperty> annotation = empty();

        if (context.getAnnotatedElement().isPresent()) {
            annotation = annotation.map(Optional::of).orElse(findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
        }
        if (context.getBeanPropertyDefinition().isPresent()) {
            annotation = annotation.map(Optional::of).orElse(findPropertyAnnotation(context.getBeanPropertyDefinition().get(),ApiModelProperty.class));
        }
        //必须是有ApiModelProperty注解的字段，并且beanPropertyDefinitionOpt带有注解
        if (annotation.isPresent() && context.getBeanPropertyDefinition().isPresent()) {
            BeanPropertyDefinition beanPropertyDefinition = context.getBeanPropertyDefinition().get();

            //获取到注解字段
            AnnotatedField field = beanPropertyDefinition.getField();
            //获取到字段所在的类
            Class<?> clazz = field.getDeclaringClass();
            //获取类中所有字段
            Field[] declaredFields = clazz.getDeclaredFields();
            Field declaredField;//获取当前字段的Field

            try {
                declaredField = clazz.getDeclaredField(field.getName());
            } catch (NoSuchFieldException | SecurityException e) {
                log.error("", e);
                return;
            }

            //获取当前字段在数组中的位置。然后设置position属性
            int indexOf = ArrayUtils.indexOf(declaredFields, declaredField);
            if (indexOf != -1) {
                context.getBuilder().position(indexOf);
            }
        }
    }
}